import CrvRequest from '@/utils/httprequest'
import { BASE_URL, TIME_OUT } from '@/serviceapi/config'

import localCache from '@/utils/cache'

import ToastUtil from '@/utils/toast'

//1:请求实例
const crvRequest: CrvRequest = new CrvRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  headers: {
    'Content-Type': 'application/json'
  },
  crvInterceptors: {
    requestInterceptor(config) {
      const token = localCache.getToken()
      if (token) {
        if (config.headers) {
          config.headers.Authorization = `Bearer ${token}`
        }
      }
      ToastUtil.showLoading('请求中...')

      return config
    },
    resposeInterceptor(res) {
      ToastUtil.closeLoading()
      console.log('拦截到的响应是', res.data)
      const data = res.data
      if (res.data.code != 0) {
        ToastUtil.showError(data.message ?? '请求失败~')
      } else {
        return data
      }
    },
    resposeInterceptorCatch(err) {
      console.log('请求异常', err)
      ToastUtil.closeLoading()
      ToastUtil.showError(err.message ?? '请求失败~')
      return err
    },
    requestInterceptorCatch(error) {
      ToastUtil.closeLoading()
      return error
    }
  }
})

export default crvRequest
